; 递归版
(define (product term a next b)
    (if (> a b)
        1
        (* (term a) (product term (next a) next b))))

; 迭代版
(define (product term a next b)
    (define (iter a reslut)
        (if (> a b)
            reslut
            (iter (next a) (* (term a) reslut))))
    (iter a 1))

; 测试过程
(define (identity x) x)
(define (next a) (+ a 1))

; 阶乘
(define (factorial n)
    (define (identity x) x)
    (define (next a) (+ a 1))
    (product identity 1 next n))

; 首先观察出来的规律，要求 n 是偶数
(define (jw n)
    (define (term x)
        (if (= x 2)
            (/ 2.0 3.0)
            (*  (/ x (- x 1))
                (/ x (+ x 1)))))
    (define (next x) (+ x 2))
    (product term 2 next n))

; 改进，要求 n 是整数即可
(define (jw n)
    (define (term x)
        (if (= x 2)
            (/ 2.0 3.0)
            (*  (/ x (- x 1))
                (/ x (+ x 1)))))
    (define (next x) (+ x 2))
    (product term 2 next (* 2 n)))

; 后面观察出来的规律，要求 n 是整数即可
(define (jw n)
    (define (numerator i)
        (if (odd? i)
            (+ i 1)
            (+ i 2)))
    (define (denominator i)
        (if (odd? i)
            (+ i 2)
            (+ i 1)))
    (define (term i)
        (/ (numerator i) (denominator i)))
    (define (next i)
        (+ i 1))
    (product term 1 next n))

; 改进，要求 n 是整数即可
(define (jw n)
    (define (term i)
        (if (odd? i)
            (/  (+ i 1)
                (+ i 2))
            (/  (+ i 2)
                (+ i 1))))
    (define (next i) (+ i 1))
    (product term 1 next n))

(define (cal-pi n)
    (* (jw n) 4.0))

(display "\n========================================\n")
(display (product identity 1 next 7))
(newline)
(display (factorial 7))
(newline)
(display (jw 10))
(newline)
(display (cal-pi 10000))
(display "\n========================================\n")
